package ruifeng.zcj.happymahjony.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.media.MediaPlayer;

public class PlayUtils {

	/**
	 * 播放音频<br/>
	 */
	@SuppressWarnings("resource")
	public static void play(Context context, byte[] data) {
		try {
			// create temp file that will hold byte array
			File temp = File.createTempFile("hlkk", "audio", context.getCacheDir());
			temp.deleteOnExit();
			FileOutputStream fos = new FileOutputStream(temp);
			fos.write(data);
			fos.close();

			// Tried reusing instance of media player
			// but that resulted in system crashes...
			MediaPlayer mediaPlayer = new MediaPlayer();

			// Tried passing path directly, but kept getting
			// "Prepare failed.: status=0x1"
			// so using file descriptor instead
			FileInputStream fis = new FileInputStream(temp);
			mediaPlayer.setDataSource(fis.getFD());

			mediaPlayer.prepare();
			mediaPlayer.start();

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	/**
	 * 播放音频<br/>
	 */
	@SuppressWarnings("resource")
	public static void playLoop(Context context, byte[] data,boolean isLoop) {
		try {
			// create temp file that will hold byte array
			File temp = File.createTempFile("hlkk", "audio", context.getCacheDir());
			temp.deleteOnExit();
			FileOutputStream fos = new FileOutputStream(temp);
			fos.write(data);
			fos.close();

			// Tried reusing instance of media player
			// but that resulted in system crashes...
			MediaPlayer mediaPlayer = new MediaPlayer();
			if (isLoop == true){
				mediaPlayer.setLooping(true);
			}

			// Tried passing path directly, but kept getting
			// "Prepare failed.: status=0x1"
			// so using file descriptor instead
			FileInputStream fis = new FileInputStream(temp);
			mediaPlayer.setDataSource(fis.getFD());

			mediaPlayer.prepare();
			mediaPlayer.start();

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
